# -*- coding: utf-8 -*-
# @Time        :2025/8/19 10:13
# @Author      :文刀水寿
# @File        : upimg_cos.py
"""
 @Description :
"""
from qcloud_cos import CosConfig

from FS_RPA import settings
from qcloud_cos import CosS3Client
from qcloud_cos.cos_exception import CosClientError, CosServiceError
import sys
import os
import logging


def upimg(image):
    secret_id = "AKIDmY863uy8C7pNlxylbQ6a8FE2d1CAuQjp"
    secret_key = "0pSt9GUdcP1Re7TdaMxOehFbjeM3d1CA"
    Bucket = "lingji-test-1334771076"
    region = "ap-nanjing"  # 替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
    token = None  # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
    scheme = "https"  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
    config = CosConfig(
        Region=region,
        SecretId=secret_id,
        SecretKey=secret_key,
        Token=token,
        Scheme=scheme,
    )
    client = CosS3Client(config)

    absolute_path = os.path.join(settings.MEDIA_ROOT, image)  # 转换为绝对路径
    # 使用高级接口断点续传，失败重试时不会上传已成功的分块(这里重试10次)
    for i in range(0, 10):
        try:
            response = client.upload_file(
                Bucket=Bucket,
                Key="images/" + image,
                LocalFilePath=absolute_path,
            )
            url = client.get_object_url(Bucket=Bucket, Key="images/" + image)
            return url
        except CosClientError or CosServiceError as e:
            print(e)
            return None


if __name__ == '__main__':
    upimg('Justin7635.png')
